package com.sduept.nwld.dataview.controller.core;

import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.services.ManagementUnitService;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.utils.PingYinUtil;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Named
@ViewScoped
public class PrimaryAndSecondaryScopeSelectorController extends AbstractController {
	//TODO: 该类 更换了ManagementUnitService 实现，需要优化，暂时把错误去掉
	/**
	 * 
	 */
	private static final long serialVersionUID = 1909386949652951315L;

	@Autowired
	private ManagementUnitService unitService;
	@Autowired
	private SubstationLedgerManager stationLedgerM;
	private TreeNode scopeTree; // 一二次设备检修范围选择树
	private TreeNode selectedNode;
	
	private String dept;
	
	private List<ManagementUnitDict> allMaintenanceScopes;
	
	@PostConstruct
	public void init() {
		try {
			allMaintenanceScopes = unitService.getAllMaintenanceScopes();
			genPrimaryAndSecodaryScopeTree();
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取所有的检修范围出错");
		}
	}
	
	/**
	 * 构造一二次设备检修范围选择树
	 */
	public void genPrimaryAndSecodaryScopeTree() {
		scopeTree = new LibTreeNode("Root", null);
		try {
			String rootName = unitService.getManagementUnitRoot();
			if(StringUtils.isEmpty(rootName)) {
				rootName = "南方电网";
			}
			LibTreeNode root = new LibTreeNode("root",rootName, scopeTree);
			recursionGenScopeTree(null, root);
			root.setExpanded(true);
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取部门根节点失败");
		}
	}
	/**
	 * 递归生成树节点
	 * @param pid
	 * @param root
	 */
	private void recursionGenScopeTree(String pid,TreeNode root) {
		List<ManagementUnitDict> childs = getUnitsByPidFromList(pid);
		for (ManagementUnitDict unit : childs) {
			LibTreeNode childNode = new LibTreeNode("maintenanceScope",unit, root);
			recursionGenScopeTree(unit.getId(), childNode);
		}
	}
	/**
	 * 根据pid，从allMaintenanceScopes中获取pid符合条件的记录
	 * @param pid
	 * @return 
	 */
	private List<ManagementUnitDict> getUnitsByPidFromList(String pid) {
		List<ManagementUnitDict> result = new ArrayList<ManagementUnitDict>();
		if(null == pid) {
			for (ManagementUnitDict unit : allMaintenanceScopes) {
				if(StringUtils.isEmpty(unit.getPid())) {
					result.add(unit);
				}
			}
		} else {
			for (ManagementUnitDict unit : allMaintenanceScopes) {
				if(pid.equals(unit.getPid())) {
					result.add(unit);
				}
			}
		}
		sort(result);
		return result;
	}
	/**
	 * 将ManagementUnitDict按ordered从高到低排序
	 * @param List<ManagementUnitDict>
	 */
	private void sort(List<ManagementUnitDict> list) {
		Collections.sort(list,new Comparator<ManagementUnitDict> () {
			@Override
			public int compare(ManagementUnitDict o1, ManagementUnitDict o2) {
				return o2.getOrdered()-o1.getOrdered();
			}
		});
	}
	
	/**
	 * 一二次设备检修范围
	 */
	public List<String> completePrimaryAndSecondaryScope(String query) {
		List<String> result = new ArrayList<String>();
		for (ManagementUnitDict dict : allMaintenanceScopes) {
			String pName = PingYinUtil.getPingYinHeader(dict.getName());
			if(pName.contains(query)) {
				result.add(dict.getName());
			}
		}
		return result;
	}
	
	/**
	 * 增加快速筛选功能，根据查询的部门重新构造树
	 * @param event
	 */
	public void autoCompleteTree(SelectEvent event) {
		Object item = event.getObject();
		if (null != item) {
			scopeTree = new DefaultTreeNode();
			try {
				ManagementUnitDict unit = unitService.getManagementUnitByName(item.toString());
				new LibTreeNode("maintenanceScope",unit, scopeTree);
			} catch (ManagementUnitException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 清空快速筛选条件时，需要重新构造树
	 */
	public void refreshTree() {
		dept = null;
		selectedNode = null;
		genPrimaryAndSecodaryScopeTree();
	}
	
	public void selectDepart() {
		if("maintenanceScope".equals(selectedNode.getType())) {
			ManagementUnitDict select = (ManagementUnitDict) selectedNode.getData();
			PrimeFaces.current().dialog().closeDynamic(select);
		} else {
			selectedNode = null;
			alertErrorMessage("请选择正确的部门");
		}
	}
	
	/**
	 * 选中树节点
	 * @param event
	 */
	public void onNodeSelect(NodeSelectEvent event) {
		selectedNode = event.getTreeNode();
	}
	
	/**
	 * 展开检修范围树节点
	 * @param event
	 */
	public void onNodeExpand(NodeExpandEvent event) {
		TreeNode selectedNode = event.getTreeNode();
		if("root".equals(selectedNode.getType())) {
			for (ManagementUnitDict unit : allMaintenanceScopes) {
				new LibTreeNode("maintenanceScope",unit, selectedNode);
			}
		}
	}
	
	public String getDept() {
		return dept;
	}

	public void setDept(String dept) {
		this.dept = dept;
	}

	public TreeNode getSelectedNode() {
		return selectedNode;
	}

	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = selectedNode;
	}

	public TreeNode getScopeTree() {
		return scopeTree;
	}

	public void setScopeTree(TreeNode scopeTree) {
		this.scopeTree = scopeTree;
	}

}
